package org.example.protocol.modules;

import org.artifact.core.server.ServerContext;
import org.artifact.core.context.session.Session;
import org.artifact.core.context.packet.NetworkPacket;
import org.artifact.core.context.packet.NetworkHeader;
import org.artifact.core.context.bytebuf.IByteBuff;
import cn.hutool.core.map.MapProxy;
import java.util.function.Consumer;
import java.util.Collection;
import java.util.Map;
import java.util.List;
import org.artifact.core.constant.ArtifactErrorCode;
import org.artifact.core.util.LogicUtil;
import org.artifact.core.lang.IModule;
import org.example.protocol.structs.*;

@SuppressWarnings("unchecked")
public interface PlayerModule extends IModule{

	default int getModuleId(){
		return 6881;
	}

	/** 分发  */
	default Consumer<NetworkPacket> disp(Session session,NetworkPacket packet) {
		int method = packet.getHeader(NetworkHeader.MODULE);
		switch (method) {
			case 6890:{
				return enterGame(session,packet);
			}
			default:
				throw LogicUtil.error(ArtifactErrorCode.NOT_FOND_ACTION);
		}
	}


	/** 进入游戏 */
	default Consumer<NetworkPacket> enterGame(Session session,NetworkPacket packet) {
		MapProxy proxy = MapProxy.create(packet.getBody());
		java.lang.String loginServerId = proxy.getStr(451300935);
		java.lang.String token = proxy.getStr(110541305);
		return enterGame(session, loginServerId, token);
	}

	/** 进入游戏 */
	Consumer<NetworkPacket> enterGame(Session session, java.lang.String loginServerId, java.lang.String token);

	default Consumer<NetworkPacket> _enterGame(Session session, int index, PlayerDTO player){
		return (NetworkPacket packet) -> {
                if (packet == null){
                    packet = new NetworkPacket();
					packet.setHeader(NetworkHeader.METHOD, 6881);
                    packet.setHeader(NetworkHeader.METHOD, 6890);
                } else {
                    packet.getBody().clear();
                }

				packet.getBody().put(100346066,index);
				packet.getBody().put(-985752863,player);
				session.send(packet);
			};
	}


	/** 推送 */
	default void notifyPlayer(Session session, java.lang.String loginServerId, java.lang.String token){
		NetworkPacket packet = new NetworkPacket();
		packet.setHeader(NetworkHeader.METHOD, 6881);
        packet.setHeader(NetworkHeader.METHOD, 17290);
		packet.getBody().put(451300935,loginServerId);
		packet.getBody().put(110541305,token);
		session.send(packet);
	}

	default void notifyPlayer(Collection<Session> sessions, java.lang.String loginServerId, java.lang.String token){
		NetworkPacket packet = new NetworkPacket();
		packet.setHeader(NetworkHeader.METHOD, 6881);
        packet.setHeader(NetworkHeader.METHOD, 17290);
		packet.getBody().put(451300935,loginServerId);
		packet.getBody().put(110541305,token);

		IByteBuff byteBuff = ServerContext.me().getByteBuffFactory().allocate();
		packet.forByteBuff(byteBuff);
		byte[] data = byteBuff.array();
		for (Session session : sessions) {
			session.send(data);
		}
	}

}